<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test websocketHandler</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<hr/>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<hr/>
<div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;
    //判断浏览器是否支持websocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/myWebSocketHandler");

        websocket.onopen = function (event) {
            setMessageInnerHTML("WebSocket连接成功");
            console.log(event);
        };

        websocket.onerror = function (event) {
            setMessageInnerHTML("WebSocket连接出错");
            console.log(event);
        };

        websocket.onmessage = function (event) {
            setMessageInnerHTML("来自服务端的消息：" + event.data);
            console.log(event);
        };

        websocket.onclose = function (event) {
            setMessageInnerHTML("WebSocket连接关闭");
            console.log(event);
        };

    } else {
        alert("当前浏览器不支持WebSocket")
    }
    function setMessageInnerHTML(message) {
        document.getElementById("message").innerHTML += message + "<br/>";
    }
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
    function closeWebSocket() {
        websocket.close();
    }
    window.onunload = closeWebSocket;
</script>

</html>